import fs from "fs-extra";
import fg from "fast-glob";
import path from "path";
import { toolchain } from "../toolchain.js";

export class Svnmv {
    public async move(): Promise<void> {
        if (!toolchain.opts.input || !toolchain.opts.target) return;
        if (!toolchain.opts.output) {
            console.error('no output');
            return;
        }

        // const files = await fg('*.*', { cwd: path.join(toolchain.opts.projectRoot, toolchain.opts.input), ignore: ['*.meta'] });
        // for (const f of files) {
        //     const file = path.join(toolchain.opts.projectRoot, toolchain.opts.input, f).replaceAll('\\', '/');
        //     const target = path.join(toolchain.opts.projectRoot, toolchain.opts.target, f).replaceAll('\\', '/');
        //     exec(`svn mv "${file}" "${target}" & svn mv "${file}.meta" "${target}.meta"`, (error) => {
        //         if (error) console.error(error);
        //     });
        // }

        await fs.writeFileSync(toolchain.opts.output, '');

        if (toolchain.opts.mvSubDirs) {
            const i = path.join(toolchain.opts.projectRoot, toolchain.opts.input);
            const subDirs = await fs.readdir(i);
            for (const sd of subDirs) {
                const s = path.join(i, sd);
                const t = path.join(toolchain.opts.projectRoot, toolchain.opts.target, sd);
                if (!fs.existsSync(t)) {
                    fs.appendFile(toolchain.opts.output, `svn mv "${s}" "${t}"\n`);
                    fs.appendFile(toolchain.opts.output, `svn mv "${s}.meta" "${t}.meta"\n`);
                }
            }
        } else {
            const files = await fg('*', { cwd: path.join(toolchain.opts.projectRoot, toolchain.opts.input), onlyFiles: false });
            for (const f of files) {
                const file = path.join(toolchain.opts.projectRoot, toolchain.opts.input, f).replaceAll('\\', '/');
                const target = path.join(toolchain.opts.projectRoot, toolchain.opts.target, f).replaceAll('\\', '/');
                fs.appendFile(toolchain.opts.output, `svn mv "${file}" "${target}"\n`);
                // console.log(`svn mv "${file}" "${target}"`);
                // console.log('');
            }
        }

        // console.log('');
    }
}

